package com.csp.mingyue.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csp.mingyue.common.core.constant.UserConstants;
import com.csp.mingyue.system.api.entity.SysMenu;
import com.csp.mingyue.system.api.vo.MetaVo;
import com.csp.mingyue.system.api.vo.RouterVo;
import com.csp.mingyue.system.mapper.SysMenuMapper;
import com.csp.mingyue.system.service.SysMenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author Strive
 * @since 2023-07-21 10:36:37
 */
@Service
@RequiredArgsConstructor
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

	private final SysMenuMapper sysMenuMapper;

	@Override
	public Set<String> getMenuPermission(Long userId) {
		List<String> menuPermissions = sysMenuMapper.selectMenuPermissionByUserId(userId);
		if (CollectionUtil.isNotEmpty(menuPermissions)) {
			return menuPermissions.stream().filter(Objects::nonNull).collect(Collectors.toSet());
		}

		return null;
	}

	@Override
	public List<RouterVo> getRouters(Long userId) {
		List<SysMenu> sysMenus = sysMenuMapper.selectMenuTreeByUserId(userId);

		return this.recursionMenu(sysMenus, -1L);
	}

	/**
	 * 递归菜单，构建菜单树
	 */
	private List<RouterVo> recursionMenu(List<SysMenu> sysMenus, Long pid) {
		List<RouterVo> tree = CollUtil.newArrayList();

		for (SysMenu menu : sysMenus) {
			if (menu.getParentId().equals(pid)) {
				RouterVo router = new RouterVo();
				router.setPath("/" + menu.getPath());
				router.setName(StrUtil.toCamelCase(menu.getPath(), '/'));
				router.setComponent(menu.getComponent());
				router.setRedirect(menu.getRedirect());

				MetaVo metaVo = new MetaVo();
				metaVo.setTitle(menu.getMenuName());
				metaVo.setIsLink(menu.getIsLink());
				metaVo.setIsHide(UserConstants.IS_HIDE.equals(menu.getIsHide()));
				metaVo.setIsKeepAlive(UserConstants.IS_KEEP_ALIVE.equals(menu.getIsKeepAlive()));
				metaVo.setIsAffix(UserConstants.IS_AFFIX.equals(menu.getIsAffix()));
				metaVo.setIsIframe(UserConstants.IS_IFRAME.equals(menu.getIsIframe()));
				metaVo.setIcon(menu.getIcon());
				router.setMeta(metaVo);

				router.setChildren(recursionMenu(sysMenus, menu.getMenuId()));

				tree.add(router);
			}
		}

		return tree;
	}

	/**
	 * 递归菜单，构建菜单树
	 */
	private List<SysMenu> recursionFn(List<SysMenu> sysMenus, Long pid) {
		List<SysMenu> tree = CollUtil.newArrayList();

		for (SysMenu sysMenu : sysMenus) {
			if (sysMenu.getParentId().equals(pid)) {
				sysMenu.setChildren(recursionFn(sysMenus, sysMenu.getMenuId()));
				tree.add(sysMenu);
			}
		}

		return tree;
	}

}
